<?php

namespace app\user\controller;

use app\model\not_del\RatingScaleModel as NotDelRatingScaleModel;
use app\model\RatingScaleLogModel;
use app\model\RatingScaleQuestionModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskUserResultModel;
use app\user\service\RatingScaleService as UserRatingScaleService;
use app\admin\service\RatingScaleService;
use app\BaseController;
use app\model\RatingScaleModel;
use app\model\RatingScaleTypeModel;
use app\model\TaskModel;
use app\model\TaskRatingScaleModel;
use app\model\TaskUserModel;
use app\model\TaskUserResultContinuityModel;
use think\App;

class RatingScale extends BaseController
{
    protected RatingScaleModel $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new RatingScaleModel();
    }

    /**
     * 存储临时答案
     * @return bool|string
     */
    public function StoreTemporaryAnswers(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $value = $this->request->param('value');
            $key = 'task_id'.$task_id.'rating_scale_id'.$rating_scale_id.'uid'.$this->userData['id'];
            cache($key,$value,604800);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取临时答案
     * @return bool|string
     */
    public function ObtainTemporaryAnswers(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $key = 'task_id'.$task_id.'rating_scale_id'.$rating_scale_id.'uid'.$this->userData['id'];
            return success(cache($key));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评右边详情
     * @return bool|string
     */
    public function selfEvaluationRightInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleModel = new NotDelRatingScaleModel();
            $data = $RatingScaleModel->with([
                'ratingScaleTypeName'
            ])->find($id);
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            //是否测评过
            $is_evaluation = $SelfEvaluationResultModel->where([
                ['uid','=',$this->userData['id']],
                ['rating_scale_id','=',$id]
            ])->value('id');
            if ($is_evaluation) {
                $data['is_evaluation'] = 1;
            }else{
                $data['is_evaluation'] = 0;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评右边详情
     * @return bool|string
     */
    public function TaskEvaluationRightInfo(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $TaskModel = new TaskModel();
            $RatingScaleModel = new NotDelRatingScaleModel();
            $TaskData = $TaskModel->with([
                'userNameRoleName'
            ])->find($task_id);
            $RatingScaleData = $RatingScaleModel->with([
                'ratingScaleTypeName'
            ])->find($rating_scale_id);
            $data = [
                'rating_scale_name' => $RatingScaleData['name'],
                'task_name' => $TaskData['name'],
                'publisher' => $TaskData['user_name'].'('.$TaskData['role_name'].')',
                'is_time' => $TaskData['is_time'],
                'start_time' => $TaskData['start_time'],
                'end_time' => $TaskData['end_time'],
                'time' => date('Y-m-d H:i:s',$TaskData['time']),
                'answer_time' => $RatingScaleData['answer_time'],
                'rating_scale_type_name' => $RatingScaleData['rating_scale_type_name'],
                'result_read_auth' => $TaskData['result_read_auth'],
                'use_price' => $RatingScaleData['use_price'],
                'is_continuous' => $TaskData['is_continuous'],
                'is_redo' => $TaskData['is_redo'],
                'is_temporary' => $TaskData['is_temporary']
            ];
            //是否连续测评【0否，1是】
            if ($TaskData['is_continuous'] == 1){
                $TaskUserModel = new TaskUserModel();
                $data['continuous'] = $TaskUserModel->where([
                    ['task_id','=',$task_id],
                    ['uid','=',$this->userData['id']],
                    ['is_finish','=',0],
                    ['rating_scale_id','<>',$rating_scale_id],
                ])->field('id,task_id,rating_scale_id')->select()->toArray();
            }else{
                $data['continuous'] = [];
            }
            //是否测评过
            $TaskUserResultModel = new TaskUserResultModel();
            $is_evaluation = $TaskUserResultModel->where([
                ['uid','=',$this->userData['id']],
                ['rating_scale_id','=',$rating_scale_id]
            ])->value('id');
            if ($is_evaluation) {
                $data['is_evaluation'] = 1;
            }else{
                $data['is_evaluation'] = 0;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表类型导航
     * @return false|string
     */
    public function typeNav(): bool|string
    {
        try {
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $RatingScaleTypeModel = new RatingScaleTypeModel();
            $list = $RatingScaleTypeModel->field('id,name')->where($where)->withCount('IsSelfEvaluation')->order('sort asc')->select()->toArray();
            $data = [];
            foreach ($list as $item){
                if ($item['is_self_evaluation_count'] == 0) continue;
                $data[] = $item;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评量表列表
     * @return false|string
     */
    public function selfEvaluationRatingScaleList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', '=', $param['type_id']];
            }
            $where[] = ['is_self_evaluation','=',1];
            $where[] = ['channel','=',1];
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $data = $this->mode->where($where)->order('id,is_recommend','desc')->paginate($param['pageSize'])->toArray();
            $RatingScaleLogModel = new RatingScaleLogModel();
            foreach ($data['data'] as &$item){
                $evaluation_num = $RatingScaleLogModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['source','=',2],
                    ['rating_scale_id','=',$item['id']],
                ])->column('uid');
                $item['evaluation_num'] = count(array_unique($evaluation_num));
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评列表
     * @return bool|string
     */
    public function taskList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $TaskUserModel = new TaskUserModel();
            $taskIds = $TaskUserModel->where([
                ['uid','=',$this->userData['id']],
                ['is_finish','=',0]
            ])->column('task_id');
            $taskIds = array_unique($taskIds);
            if (!empty($taskIds)) {
                $where[] = ['id','in',$taskIds];
            }else{
                $where[] = ['id','=',-1];
            }
            $where[] = ['status','=',2];
            $TaskModel = new TaskModel();
            $data = $TaskModel->where($where)
                ->with([
                    'userNameRoleName' => function($query){
                        $query->with(['roleName']);
                    }
                ])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item){
                $item['role_name'] = $item['role_name'] ?? '超级管理员';
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取任务量表名称列表
     * @return false|string
     */
    public function getTaskRatingScaleNameList(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $data = $TaskRatingScaleModel->where('task_id','=',$task_id)
                ->with(['ratingScale'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取任务量表列表
     * @return false|string
     */
    public function getTaskRatingScaleList(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $where = [];
            $where[] = ['task_id','=',$task_id];
            $where[] = ['uid','=',$this->userData['id']];
            $TaskUserModel = new TaskUserModel();
            $data = $TaskUserModel->where($where)
                ->with([
                    'ratingScale'
                ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取任务量表列表
     * @return false|string
     */
    public function getTaskRatingScaleList2(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $where = [];
            $where[] = ['task_id','=',$task_id];
            $where[] = ['uid','=',$this->userData['id']];
            $TaskUserModel = new TaskUserModel();
            $data = $TaskUserModel->where($where)
                ->with([
                    'ratingScale'
                ])->select()->toArray();
            $TaskModel = new TaskModel();
            $taskInfo = $TaskModel->field('id,name,is_time,start_time,end_time')->find($task_id);
            return success([
                'task_info' => $taskInfo,
                'list' => $data
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取量表详情
     * @return false|string
     */
    public function getTaskRatingScaleInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserModel = new TaskUserModel();
            $info = $TaskUserModel->where('id','=',$id)
                ->with([
                    'ratingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    },
                    'task'
                ])->find();
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $RatingScaleQuestionModel = new RatingScaleQuestionModel();
            $info['question_num'] = $RatingScaleQuestionModel->where('rating_scale_id','=',$info['rating_scale_id'])->count();
            $RatingScaleService = new RatingScaleService($this->app);
            $question = $RatingScaleService->GetQuestion($info['rating_scale_id']);
            return success([
                'question' => $question,
                'info' => $info
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 提交自我测评结果
     * @return false|string
     */
    public function submitSelfEvaluationResults(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'rating_scale_id|量表ID' =>  'require',
                'answer_role|答题角色' =>  'require',
                'finish_used_time|用户完成用时' =>  'require',
            ]);
            $lock = env('REDIS_PROJECT').'submitSelfEvaluationResults'.$this->userData['id'].'rating_scale_id'.$param['rating_scale_id'];
            if (cache($lock)) throw new \Exception('一分钟内不可重复提交！');
            cache($lock,1,60);
            $RatingScaleService = new UserRatingScaleService($this->app);
            if (!$RatingScaleService->generateReport([
                'company_id' => $this->userData['company_id'],//公司
                'areas_id' => $this->userData['areas_id'],//区域
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],//答题用户ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'answer_role' => $param['answer_role'],//答题角色【1 用户，2 家长】
                'userAnswer' => $param['question_answer']??[],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
                'sex' => $this->userData['sex']
            ],2)) throw new \Exception('提交失败！'.$RatingScaleService->message.$RatingScaleService->line);
            $this->mode->commit();
            return success([
                'result_id' => $RatingScaleService->ResultId,
                'is_valid' => $RatingScaleService->is_valid
            ],'提交成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 提交任务测评结果
     * @return false|string
     */
    public function submitTaskEvaluationResults(): bool|string
    {
        $TaskUserModel = new TaskUserModel();
        $TaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'task_id|任务ID' =>  'require',
                'task_user_id|用户任务表ID' =>  'require',
                'rating_scale_id|量表ID' =>  'require',
                'answer_role|答题角色' =>  'require',
                'finish_used_time|用户完成用时' =>  'require',
            ]);
            $lock = 'user_submitTaskEvaluationResults'.$this->userData['id'].'task_user_id'.$param['task_user_id'];
            if (cache($lock)) throw new \Exception('操作过快，请稍后再试~');
            cache($lock,1,30);
            //不可重复提交
            $TaskUserInfo = $TaskUserModel->field('id,uid,is_finish')->find($param['task_user_id']);
            if (!$TaskUserInfo || $TaskUserInfo['uid'] != $this->userData['id']) throw new \Exception('参数错误！');
            if ($TaskUserInfo['is_finish'] == 1) throw new \Exception('不可重复提交！');
            $RatingScaleService = new UserRatingScaleService($this->app);
            if (!$RatingScaleService->generateReport([
                'company_id' => $this->userData['company_id'],//公司
                'areas_id' => $this->userData['areas_id'],//区域
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],//答题用户ID
                'task_id' => $param['task_id'],//任务ID
                'task_user_id' => $param['task_user_id'],//用户任务表ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'answer_role' => $param['answer_role'],//答题角色【1 用户，2 家长】
                'userAnswer' => $param['question_answer']??[],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
                'sex' => $this->userData['sex']
            ],1))
                throw new \Exception($RatingScaleService->message.'line:'.$RatingScaleService->line);
            $TaskUserInfo->save([
                'is_finish' => 1,
                'result_id' => $RatingScaleService->ResultId,
            ]);
            $TaskUserModel->commit();
            return success([
                'result_id' => $RatingScaleService->ResultId,
                'data' => $RatingScaleService->resultData,
                'is_valid' => $RatingScaleService->is_valid
            ],'提交成功！');
        } catch (\Exception $e) {
            $TaskUserModel->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 提交任务连续测评结果
     * @return false|string
     */
    public function submitTaskContinuousEvaluation(): bool|string
    {
        $param = $this->request->param();
        try {
            $this->validate($param,[
                'task_id|任务ID' =>  'require',
                'task_user_id|用户任务表ID' =>  'require',
                'rating_scale_id|量表ID' =>  'require',
                'answer_role|答题角色' =>  'require',
                'finish_used_time|用户完成用时' =>  'require',
            ]);
            //不可重复提交
            $TaskUserResultContinuityModel = new TaskUserResultContinuityModel();
            $is_finish = $TaskUserResultContinuityModel->where([
                'task_user_id' => $param['task_user_id'],
                'rating_scale_id' => $param['rating_scale_id'],
            ])->value('id');
            if ($is_finish) throw new \Exception('不可重复提交！');
            $RatingScaleService = new UserRatingScaleService($this->app);
            if (!$RatingScaleService->generateReport([
                'company_id' => $this->userData['company_id'],//公司
                'areas_id' => $this->userData['areas_id'],//区域
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],//答题用户ID
                'task_id' => $param['task_id'],//任务ID
                'task_user_id' => $param['task_user_id'],//用户任务表ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'answer_role' => $param['answer_role'],//答题角色【1 用户，2 家长】
                'userAnswer' => $param['question_answer']??[],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
                'sex' => $this->userData['sex']
            ],3)) throw new \Exception($RatingScaleService->message);
            return success([
                'result_id' => $RatingScaleService->ResultId,
                'is_valid' => $RatingScaleService->is_valid
            ],'提交成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }



}
